#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Person{
public:
    Person(const char* name,int age)
    : _name(new char[strlen(name)+1]())
    , _age(age)
    {
        strcpy(_name,name);
    }

    Person(const Person & rhs)
    : _name(new char[strlen(rhs._name) + 1]())
    , _age(rhs._age)
    {
        strcpy(_name,rhs._name);
    }

    Person & operator=(const Person & rhs){
        if(this != &rhs){
            delete [] _name;
            _name = new char[strlen(rhs._name) + 1]();
            strcpy(_name,rhs._name);
            _age = rhs._age;
        }
        return *this;
    }

    ~Person(){
        if(_name){
            delete [] _name;
            _name = nullptr;
        }
    }

    void display() const{
        cout << _name << " " << _age << endl;
    }
private:
    char* _name;
    int _age;
};

class Employee
:public Person
{
public:
    Employee(const char * name,int age,const char * department,double salary)
    : Person(name,age)
    , _department(new char[strlen(department) + 1]())
    , _salary(salary)
    {
        _totalSalary += _salary;
        ++_totalNum;
        strcpy(_department,department);
    }


    Employee(const Employee & rhs)
    : Person(rhs) //显式调用基类的拷贝构造函数
    , _department(new char[strlen(rhs._department)+1]())
    , _salary(rhs._salary)
    {
        _totalSalary += _salary;
        ++_totalNum;
        strcpy(_department,rhs._department);
    }

    Employee & operator=(const Employee & rhs){
        if(this != &rhs){
            //显式调用基类的赋值运算符函数
            Person::operator=(rhs);
            _totalSalary -= _salary;
            delete [] _department;
            _department = new char[strlen(rhs._department) + 1]();
            strcpy(_department,rhs._department);
            _salary = rhs._salary;
            _totalSalary += _salary;
        }
        return *this;
    }

    ~Employee(){
        if(_department){
            _totalSalary -= _salary;
            --_totalNum;
            delete [] _department;
            _department = nullptr;
        }
    }

    void display() const{
        Person::display();
        cout << _department << " " << _salary << endl;
    }
    
    static void showAverage(){
        if(_totalNum != 0){
            cout << _totalSalary/_totalNum << endl;
        }else{
            cout << "no Employee!" << endl;
        }
    }


private:
    char* _department;
    double _salary;
    static double _totalSalary;
    static int _totalNum;
};
double Employee::_totalSalary = 0;
int Employee::_totalNum = 0;


void test0(){
    Employee e1("Bob",25,"sales",9000);
    Employee e2("Tim",28,"HR",6000);
    Employee e3 = e2;
    e3.display();

    cout << endl;
    e1 = e2;
    e1.display();
    Employee::showAverage();
}

int main(void){
    test0();
    return 0;
}


